<template>
  <div class="tempbigbox">
    <!-- 左边整体内容模块 -->
    <div class="console">
      <!-- 添加ref以便调用getData方法 -->
      <CardList ref="cardListRef"></CardList>

      <div class="column column2">
        <!-- <ActiveUser></ActiveUser>
        <SalesOverview></SalesOverview> -->
        <div class="page-content">
          <h3 style="margin-bottom: 20px">推广员列表</h3>
          <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick" style="margin-top: 20px">
            <el-tab-pane label="推广员列表" name="0"> </el-tab-pane>
            <el-tab-pane label="审核列表" name="1"> </el-tab-pane>
          </el-tabs>
          <el-form :model="searchForm" ref="searchFormRef" label-width="100px" style="margin-top: 20px">
            <el-row :gutter="24">
              <el-col :span="6">
                <el-form-item label="推广员信息：" prop="name">
                  <el-input v-model="searchForm.name" placeholder="请输入推广员信息" clearable @blur="getData" />
                </el-form-item>
              </el-col>
              <!-- <form-select label="等级" prop="levelId" v-model="searchForm.levelId" :options="gradeOptions" /> -->
              <el-col :span="6">
                <el-form-item label="等级：" prop="levelId">
                  <el-select v-model="searchForm.levelId" clearable placeholder="请选择" @change="getData">
                    <el-option v-for="item in gradeOptions" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="手机号：" prop="bindPhone">
                  <el-input v-model="searchForm.bindPhone" placeholder="请输入手机号" clearable @blur="getData" />
                </el-form-item>
              </el-col>
              <div class="databox">
                <label class="el-form-item__label">创建时间：</label>
                <el-date-picker label="创建时间：" v-model="datavalue" type="datetimerange" start-placeholder="开始日期"
                  end-placeholder="结束日期" format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd"
                  time-format="A hh:mm:ss" @change="timeChange" clearable />
              </div>
            </el-row>
            <div style="display: flex; justify-content: space-between">
              <div>
                <!-- <el-button style="margin-top: 20px" @click="getData">搜索</el-button>
                <el-button style="margin-top: 20px" @click="reset">重置</el-button> -->
                <el-button style="margin-top: 20px" @click="showDialog('add')">新增推广员</el-button>
              </div>
              <div class="action-bar" style="display: flex;">
                <el-button v-ripple @click="handleDownloadTemplate" :loading="downloadLoading"
                  style="margin-right: 20px;">
                  <el-icon>
                    <Download />
                  </el-icon>
                  下载模板
                </el-button>
                <el-upload class="upload-component" :action="excelServer" :headers="headers" :show-file-list="false"
                  :on-success="handleImportSuccess" :on-error="handleImportError" :before-upload="beforeImportUpload"
                  :disabled="uploadLoading">
                  <el-button type="primary" :loading="uploadLoading">
                    <el-icon>
                      <Upload />
                    </el-icon>
                    导入推广员
                  </el-button>
                </el-upload>
              </div>
            </div>
          </el-form>
          <art-table :data="tableData" selection :currentPage="pageNum" :pageSize="pageSize" :total="pagetotal"
            @current-change="currentChange" @size-change="sizeChange">
            <template #default>
              <el-table-column label="推广员信息" prop="avatar" #default="scope" width="300px">
                <div class="user" style="display: flex; align-items: center">
                  <img :src="scope.row.avatar" alt="" style="width: 50px; height: 50px; border-radius: 50%"
                    v-if="scope.row.avatar" />
                  <div>
                    <p class="user-name">{{ scope.row.name }}</p>
                    <p class="email">ID:{{ scope.row.memberId }}</p>
                  </div>
                </div>
              </el-table-column>
              <el-table-column label="绑定手机号" prop="bindPhone" align="center" />
              <el-table-column label="申请手机号" prop="applyPhone" align="center" />
              <el-table-column label="邀请人" prop="parentName" align="center"> </el-table-column>
              <el-table-column label="等级" prop="levelName" align=" center" />
              <el-table-column label="累计邀请人数(人)" prop="dep" align="center" v-if="activeName === '0'">
                <template #default="scope">
                  <div>累计发展客户数：{{ scope.row.totalCustomers }}人</div>
                  <div>当前绑定客户数：{{ scope.row.currentCustomers }}人</div>
                  <div>累计邀请推广员数：{{ scope.row.totalInvitedPromoters }}人</div>
                  <div>当前邀请推广员数：{{ scope.row.currentInvitedPromoters }}人</div>
                </template>
              </el-table-column>
              <el-table-column label="已结算收益(元)" prop="settledIncome" align="center" v-if="activeName === '0'">
                <template #default="scope">
                  {{ scope.row.settledIncome / 100 }}
                </template>
              </el-table-column>
              <el-table-column label="待结算收益(元)" prop="unsettledIncome" v-if="activeName === '0'" align="center">
                <template #default="scope">
                  {{ scope.row.unsettledIncome / 100 }}
                </template>
              </el-table-column>
              <el-table-column label="加入时间" prop="joinTime" sortable align="center" />
              <el-table-column label="状态" prop="promoterStatus" align="center">
                <template #default="scope">
                  <el-tag :type="getTagType(scope.row.promoterStatus)">
                    {{ scope.row.promoterStatus < 4 ? buildTagText(scope.row.promoterStatus) : '' }} </el-tag>
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作" width="300px" align="center">
                <template #default="scope">
                  <el-button type="primary" size="default" plain v-if="activeName === '1'"
                    @click="toExamine(scope.row, 1)">通过</el-button>
                  <el-button type="danger" size="default" plain
                    v-if="activeName === '1' && scope.row.promoterStatus !== 2"
                    @click="refuse(scope.row)">拒绝</el-button>
                  <button-table type="edit" @click="showDialog('edit', scope.row)" style="margin-left: 10px" />
                  <!-- <button-table type="delete" @click="deleteUser" /> -->
                </template>
              </el-table-column>
            </template>
          </art-table>

          <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '添加用户' : '修改邀请人'" width="20%"
            :close-on-click-modal="false">
            <el-form ref="formRef" :model="formData" :rules="rules" label-width="150px">
              <el-form-item label="当前邀请人信息" prop="name" v-if="dialogType === 'edit'">
                <el-input v-model="formData.name" :disabled="!isEdit" />
              </el-form-item>
              <el-form-item label="推广员手机号" prop="meMobile" v-if="dialogType === 'add'">
                <el-input v-model="formData.meMobile" />
              </el-form-item>
              <el-form-item label="上级推广员手机号" prop="leaderMobile" v-if="dialogType === 'add'">
                <el-input v-model="formData.leaderMobile" />
              </el-form-item>
              <el-form-item label="选择邀请人" prop="parentId" v-if="dialogType === 'edit'">
                <el-select v-model="formData.parentId" filterable placeholder="请选择邀请人">
                  <el-option v-for="item in parentOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-form>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit">提交</el-button>
              </div>
            </template>
          </el-dialog>
        </div>
      </div>

      <!-- <div class="column column2">
        <NewUser></NewUser>
        <NewUser></NewUser>
      </div> -->
      <el-dialog v-model="refuseDialog" title="填写拒绝原因" width="30%" :close-on-click-modal="false">
        <el-input v-model="formData.rejectReason" type="textarea" :rows="4" placeholder="请输入拒绝原因" />
        <template #footer>
          <el-button @click="refuseDialog = false">取消</el-button>
          <el-button type="primary" @click="toExamine(refuseList, 2)">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import CardList from './widget/CardList.vue'
import { useSettingStore } from '@/store/modules/setting'
import { WEB_LINKS } from '@/utils/constants'
import { useCommon } from '@/composables/useCommon'
import { ACCOUNT_TABLE_DATA } from '@/mock/temp/formData'
import { FormInstance } from 'element-plus'
import { ElMessageBox, ElMessage } from 'element-plus'
import type { FormRules } from 'element-plus'
import {
  promoterList,
  updatePromote,
  promoteSelect,
  addPromote,
  levelList,
  downloadTemplate,
  updatePromoteStatus
} from '@/api/marketing'
import { useUserStore } from '@/store/modules/user'

const userStore = useUserStore()
const { accessToken } = userStore

const excelServer = `${import.meta.env.VITE_API_URL}brokerage/promoter/importXlsx`
const headers = { Authorization: `Bearer ${accessToken}` }
const uploadLoading = ref(false)

// 新增CardList组件ref用于访问其方法
const cardListRef = ref<any>(null)

// 常量定义
const EXCEL_MIME_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
const MAX_FILE_SIZE = 50 * 1024 * 1024 // 50MB

const beforeImportUpload = (file: File): boolean => {
  const isExcel = file.type === EXCEL_MIME_TYPE
  const isLt50 = file.size < MAX_FILE_SIZE

  if (!isExcel) {
    ElMessage.error('只能上传Excel文件!')
    return false
  }

  if (!isLt50) {
    ElMessage.error('文件大小不能超过50MB!')
    return false
  }

  uploadLoading.value = true
  return true
}

interface ImportResponse {
  code: string
  msg: string
  data?: any
}

const handleImportSuccess = (response: ImportResponse) => {
  uploadLoading.value = false

  if (response.code === '0') {
    ElMessage.success('导入成功')
    getData() // 刷新数据
  } else {
    ElMessage.error(response.msg || '导入失败')
  }
}

const handleImportError = (error: any) => {
  uploadLoading.value = false
  console.error('导入失败:', error)
  ElMessage.error('导入失败，请稍后重试')
}

const settingStore = useSettingStore()
const currentGlopTheme = computed(() => settingStore.systemThemeType)
const refuseDialog = ref(false)

const isEdit = ref(false)
const activeName = ref('0')

// 系统主题风格变化时，刷新页面重写渲染 Echarts
watch(currentGlopTheme, () => {
  settingStore.reload()
})

useCommon().scrollToTop()

const goPage = (url: string) => {
  // 跳转到新页面
  window.open(url)
}
const dialogType = ref('add')
const dialogVisible = ref(false)

const refuseList = ref({})
const refuse = (e: any) => {
  refuseDialog.value = true
  refuseList.value = e
}

const searchForm = reactive({
  name: '',
  bindPhone: '',
  queryStartTime: '',
  queryEndTime: '',
  levelId: ''
})
const formData = reactive({
  name: '',
  parentId: '',
  leaderMobile: '',
  meMobile: '',
  id: '',
  rejectReason: ''
})

const columns = reactive([
  { name: '用户名', show: true },
  { name: '手机号', show: true },
  { name: '性别', show: true },
  { name: '来源', show: true },
  { name: '状态', show: true },
  { name: '创建日期', show: true }
])

const searchFormRef = ref<FormInstance>()

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const tableData = ref([])
const oldParentId = ref('')
const showDialog = (type: string, row?: any) => {
  dialogVisible.value = true
  dialogType.value = type

  if (type === 'edit' && row) {
    formData.name = row.name
    formData.parentId = row.parentId
    formData.id = row.id
    oldParentId.value = row.parentId
    getParentData(row.id)
  } else {
    formData.name = ''
    formData.parentId = ''
    formData.meMobile = ''
    formData.leaderMobile = ''
    formData.leaderMobile = ''
    formData.id = ''
  }
}

const getParentData = async (id: string) => {
  const res = await promoteSelect({
    id
  })
  if (res.code === '00000') {
    parentOptions.value = res.data
  }
}

const deleteUser = () => {
  ElMessageBox.confirm('确定要注销该用户吗？', '注销用户', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(() => {
    ElMessage.success('注销成功')
  })
}

const search = () => { }

const changeColumn = (list: any) => {
  columns.values = list
}

const filterTag = (value: string, row: any) => {
  return row.status === value
}

const getTagType = (status: number) => {
  switch (status) {
    case 0:
      return 'info'
      break
    case 1:
      return 'primary'
      break
    case 2:
      return 'warning'
      break
    case 3:
      return 'danger'
      break
  }
}

const buildTagText = (status: number) => {
  let text = ''
  if (status === 0) {
    text = '待审核'
  } else if (status === 1) {
    text = '已通过'
  } else if (status === 2) {
    text = '已拒绝'
  } else if (status === 3) {
    text = '已冻结'
  }
  return text
}

const validatePasswordMatch = (rule: any, value: string, callback: (error?: Error) => void) => {
  if (value === formData.meMobile) {
    callback(new Error('手机号不能相同'))
  } else {
    callback()
  }
}

const rules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  meMobile: [
    { required: true, message: '请输入推广员手机号', trigger: ['blur', 'change'] },
    {
      min: 11,
      max: 11,
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号格式',
      trigger: 'blur'
    }
  ],
  leaderMobile: [
    // { required: true, message: '请输入上级推广员手机号', trigger: ['blur', 'change'] },
    {
      min: 11,
      max: 11,
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号格式',
      trigger: 'blur'
    },
    { validator: validatePasswordMatch, trigger: 'blur' }
  ],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  dep: [{ required: true, message: '请选择部门', trigger: 'change' }]
})

const formRef = ref<FormInstance>()

const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      dialogVisible.value = false
      if (formData.id) {
        const res = await updatePromote({
          id: formData.id,
          parentId: formData.parentId,
          oldParentId: oldParentId.value
        })
        if (res.code === '00000') {
          ElMessage.success('修改成功')
          getData()
          if (cardListRef.value) {
            cardListRef.value.getData();
          }
        }
      } else {
        const res = await addPromote({
          meMobile: formData.meMobile,
          leaderMobile: formData.leaderMobile
        })
        if (res.code === '00000') {
          ElMessage.success('新增成功')
          getData()
          if (cardListRef.value) {
            cardListRef.value.getData();
          }
        }
      }
    }
  })
}
const datavalue = ref('')
const timeChange = (e: any) => {
  if (e) {
    searchForm.queryStartTime = e[0]
    searchForm.queryEndTime = e[1]
  } else {
    searchForm.queryStartTime = ''
    searchForm.queryEndTime = ''
  }
  getData()
}

interface ListItem {
  value: string
  label: string
}
const parentOptions = ref<ListItem[]>([])
const promoterStatus = ref([1, 3])
const handleClick = (e: any) => {
  if (e.index === '0') {
    promoterStatus.value = [1, 3]
  } else {
    promoterStatus.value = [0, 2]
  }
  getData()
}
const pagetotal = ref()
const pageNum = ref(1)
const pageSize = ref(10)
const tableLoading = ref(false)

const filterEmptyValues = (obj: any) => {
  const result: any = {}
  for (const key in obj) {
    if (obj[key] !== '' && obj[key] !== null && obj[key] !== undefined) {
      result[key] = obj[key]
    }
  }
  return result
}

const formatDate = (date: string) => {
  return new Date(date)
    .toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
    .replace(/\//g, '-')
}

const getData = async () => {
  try {
    tableLoading.value = true
    searchForm.queryStartTime = searchForm.queryStartTime ? formatDate(searchForm.queryStartTime) : ''
    searchForm.queryEndTime = searchForm.queryEndTime ? formatDate(searchForm.queryEndTime) : ''
    const params = filterEmptyValues(searchForm)
    if (params.levelId) params.levelId = Number(params.levelId)
    const { code, data } = await promoterList({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      promoterStatus: promoterStatus.value,
      ...params
    })
    if (code === '00000') {
      tableData.value = data.list
      pagetotal.value = data.total
    }
  } catch (e) {
  } finally {
    tableLoading.value = false
  }
}

const reset = () => {
  searchForm.name = ''
  searchForm.levelId = ''
  searchForm.queryStartTime = ''
  searchForm.queryEndTime = ''
  searchForm.bindPhone = ''
  datavalue.value = ''
}

const currentChange = (val: number) => {
  pageNum.value = val
  getData()
}

const sizeChange = (val: number) => {
  pageSize.value = val
  pageNum.value = 1
  getData()
}

const examineLoading = ref(false)
const toExamine = async (e: any, promoterStatus: number) => {
  try {
    examineLoading.value = true
    const params: any = {
      id: e.id,
      promoterStatus
    }
    if (promoterStatus === 2) params.rejectReason = formData.rejectReason
    const res = await updatePromoteStatus(params)
    if (res.code === '00000') {
      ElMessage.success(promoterStatus === 1 ? '通过成功' : '拒绝成功')
      if (promoterStatus === 2) refuseDialog.value = false
      getData()
      // 调用CardList里的getData方法
      if (cardListRef.value) {
        cardListRef.value.getData();
      }
    } else {
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (err) {
    ElMessage.error('网络异常，请稍后重试')
  } finally {
    examineLoading.value = false
  }
}
const gradeOptions = ref<any>([])

const getLevelInfo = async () => {
  const res = await levelList()
  if (res.code === '00000') {
    gradeOptions.value = res.data
    console.log(gradeOptions.value, 'gradeOptions.value===')
  }
}

const downloadLoading = ref(false)

const handleDownloadTemplate = async () => {
  try {
    downloadLoading.value = true

    const res = await downloadTemplate()

    if (res instanceof Blob) {
      // 创建下载链接
      const link = document.createElement('a')
      link.href = URL.createObjectURL(res)
      link.download = '推广员导入模板.xlsx'
      link.style.display = 'none'
      document.body.appendChild(link)
      link.click()

      // 清理
      URL.revokeObjectURL(link.href)
      document.body.removeChild(link)

      ElMessage.success('模板下载成功')
    } else {
      ElMessage.error('下载失败')
    }
  } catch (error) {
    console.error('下载模板失败:', error)
    ElMessage.error('下载失败，请稍后重试')
  } finally {
    downloadLoading.value = false
  }
}


onMounted(() => {
  getData()
  getLevelInfo()
})
</script>

<style lang="scss" scoped>
.console {
  padding-bottom: 15px;

  :deep(.card-header) {
    display: flex;
    justify-content: space-between;
    padding: 20px 25px 5px 0;

    .title {
      h4 {
        font-size: 18px;
        font-weight: 500;
        color: var(--art-text-gray-800);
      }

      p {
        margin-top: 3px;
        font-size: 13px;

        span {
          margin-left: 10px;
          color: #52c41a;
        }
      }
    }
  }

  // 主标题
  :deep(.box-title) {
    color: var(--art-gray-900) !important;
  }

  // 副标题
  :deep(.subtitle) {
    color: var(--art-gray-600) !important;
  }

  :deep(.card-list li),
  .region,
  .dynamic,
  .bottom-wrap {
    background: var(--art-main-bg-color);
    border-radius: calc(var(--custom-radius) + 4px) !important;
  }

  .column {
    display: flex;
    justify-content: space-between;
    margin-top: var(--console-margin);
    background-color: transparent !important;
  }

  .bottom-wrap {
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    height: 300px;
    padding: 20px;
    margin-top: var(--console-margin);
    background: var(--art-main-bg-color);

    h2 {
      margin-top: 10px;
      font-size: 20px;
      font-weight: 500;
    }

    p {
      margin-top: 5px;
      font-size: 14px;
      color: var(--art-gray-600);
    }

    .button-wrap {
      display: flex;
      flex-wrap: wrap;
      width: 600px;
      margin-top: 35px;

      .btn {
        display: flex;
        justify-content: space-between;
        width: 240px;
        height: 50px;
        padding: 0 15px;
        margin: 0 15px 15px 0;
        font-size: 14px;
        line-height: 50px;
        color: var(--art-gray-800);
        text-align: center;
        cursor: pointer;
        background: var(--art-bg-color);
        border-radius: calc(var(--custom-radius) / 2 + 2px) !important;
        transition: all 0.3s;

        &:hover {
          box-shadow: 0 5px 10px rgb(0 0 0 / 5%);
          transform: translateY(-4px);
        }
      }
    }
  }
}

.page-content {
  width: 100%;
  height: 100%;
  margin-top: 20px;

  .user {
    .avatar {
      width: 40px;
      height: 40px;
      border-radius: 6px;
    }

    >div {
      margin-left: 10px;

      .user-name {
        font-weight: 500;
        color: var(--art-text-gray-800);
      }
    }
  }
}
</style>
